import javax.swing.*;
import java.awt.*;
public class DrawLineExample extends JFrame {
    int w;  //chuangti
    int h;

    public DrawLineExample(int w,int h) {
        this.w=w;   //窗体宽度
        this.h=h;   //窗体高度
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     //设置窗体的系统控件（关闭推出，最小/最大化，关闭按钮）
        setSize(this.w, this.h);  //设置窗体大小
        setLocationRelativeTo(null);    //弹出窗口默认在系统创左上角，设置位置相对(null)居中
        setVisible(true);   //窗体可见
    }

    public void paint(Graphics g) {
        super.paint(g);
        g.drawLine(50, 50, 400, 400);


        // 绘制坐标轴
        g.drawLine(10, this.h/2, this.w, this.h/2);
        g.drawLine(this.w/2, 10, this.w/2, this.h);

        // 绘制正弦曲线 (20->220)
        g.setColor( Color.blue);
        int x0, y0, x1, y1;
        x1 = 10; y1 = 10;
        for (int i = 1; i <= this.w; i++){
            x0 = x1; y0 = y1;
            x1 = (int)(i/20.0*200);
            y1 = (int)(this.h/2+(this.h/3*Math.sin(0.5*i/Math.PI)));
            g.drawLine(x0, y0, x1, y1);
        }

        // 绘制 cos 曲线 (20->220)
        g.setColor( Color.red);
        x1 = 10; y1 = 10;
        for (int i = 1; i <= this.w; i++){
            x0 = x1; y0 = y1;
            x1 = (int)(i/20.0*200);
            y1 = (int)(this.h/2+(this.h/4*Math.cos(i/Math.PI)));
            g.drawLine(x0, y0, x1, y1);
        }

        g.setColor( Color.blue);
        int r=200;
        int xx= this.w/2;
        int yy= this.h/2;

        for (int i = -yy; i < yy; i++) {
            for (int j = -xx; j < xx; j++) {
                if(i*i+j*j<r*r+2 && i*i+j*j>r*r-2 ){
                    g.drawLine(i+xx, j+yy, i+xx, j+yy);
                }
            }
        }
        g.drawOval (10, 10, 200, 200);  //画椭圆，圆形

        g.setColor( Color.black);   //设置绘图颜色
        for (int i = 0; i < 3; i++) {      //画各种图，利用随机点
            int x =(int) (Math.random()*w);
            int y =(int) (Math.random()*h/2);
            x1 =(int) (Math.random()*w);
            y1 =(int) (Math.random()*h/2);
            g.drawLine(x, y, x1,y1);    //画随机直线
            g.drawString("直线",x1,y1);
            g.drawOval (x, y, x1, y1);  //画随机圆
            g.drawString("       圆形",x1,y1+20);
            g.drawRect(x1,y1,x,y);  //画随机矩形
            g.drawString("              矩形",x1,y1+40);
        }
        g.drawString("Java绘图输出",50,50);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() ->
                new DrawLineExample(600,600));
    }
}
